package com.dtzhejiang.social.supervision.risk.engine.common.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.codelibs.minhash.MinHash;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @Author: chenwenhao
 * Date: 15:32 2020/11/23
 * Content:
 */
public class AlgorithmUtils {

    private static Analyzer analyzer = MinHash.createAnalyzer(new StandardTokenizer(), 1, 0,
            128);

    /**
     * 编辑距离相似度
     * @param testStr1
     * @param testStr2
     * @return
     */
    public static BigDecimal getSimilarityByLevenshteinDistance(String testStr1, String testStr2) {
        if (StringUtils.isBlank(testStr1) || StringUtils.isBlank(testStr2)) {
            return BigDecimal.valueOf(0);
        }
        int d = StringUtils.getLevenshteinDistance(testStr1, testStr2);
        BigDecimal distance = new BigDecimal(d);
        BigDecimal maxLength = new BigDecimal(Math.max(testStr1.length(), testStr2.length()));
        return BigDecimal.valueOf(1L).subtract(distance.divide(maxLength, 4, RoundingMode.UP));
    }

    /**
     * 获取两个字符串的相似度
     * @param testStr1
     * @param testStr2
     * @return
     */
    public static float getSimilarityByMinHash(String testStr1, String testStr2) {
        //如果存在一个字符串为空，则匹配度直接为0
        if (StringUtils.isBlank(testStr1) || StringUtils.isBlank(testStr2)) {
            return 0;
        }
        //如果两个字符串完全相同，则匹配度为1
        if (testStr1.equals(testStr2)) {
            return 1;
        }
        MinHash.compare(getHash(testStr1), getHash(testStr2));
        return MinHash.compare(getHash(testStr1), getHash(testStr2));
    }

    private static byte[] getHash(String text){
        if(StringUtils.isNotBlank(text)) {
            try {
                return MinHash.calculate(analyzer, text);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
